package cn.bluarry.weathert;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;

import cn.bluarry.weathert.gson.ForeCast;
import cn.bluarry.weathert.gson.Weather;
import cn.bluarry.weathert.util.HttpUtil;
import cn.bluarry.weathert.util.Utility;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class WeatherActivity extends AppCompatActivity {

    public DrawerLayout drawerLayout;
    private Button navbtn;

    private ScrollView weatherLayout;

    private TextView titleCity;

    private TextView titleUpgradeTime;
    private  TextView degreeText;
    private TextView weatherInfoText;

    private LinearLayout forecastLayout;

    private TextView aqiText;
    private TextView pm25text;
    private TextView comforttext;
    private TextView carWashText;
    private TextView sportText;

    private ImageView bingPicimg;

    public  SwipeRefreshLayout swipeRefresh;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //隐藏状态栏，同时Activity会伸展全屏显示
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
        //getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN);
        //getWindow().getDecorView().setSystemUiVisibility(View.INVISIBLE);
        //Activity全屏显示，但状态栏不会被隐藏覆盖，状态栏依然可见，Activity顶端布局部分会被状态遮
        //getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
        //隐藏虚拟按键
//        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);

        setContentView(R.layout.activity_weather);

        swipeRefresh=findViewById(R.id.swipe_refresh);
        swipeRefresh.setColorSchemeResources(R.color.colorPrimary);
        weatherLayout=findViewById(R.id.weather_layout);
        titleCity=findViewById(R.id.title_city);
        titleUpgradeTime=findViewById(R.id.title_update_time);
        degreeText=findViewById(R.id.degree_text);
        weatherInfoText=findViewById(R.id.weather_in_text);
        forecastLayout=findViewById(R.id.forecast_layout);
        aqiText=findViewById(R.id.aqi_text);
        pm25text=findViewById(R.id.pm25_text);
        comforttext=findViewById(R.id.comfort_text);
        carWashText=findViewById(R.id.car_wash_text);
        sportText=findViewById(R.id.sport_text);
        bingPicimg=findViewById(R.id.bing_pic_img);

        SharedPreferences  prefs= PreferenceManager.getDefaultSharedPreferences(this);
        final String wid;
        String weatherstr =prefs.getString("weather",null);
        if(weatherstr!=null){
            Weather weather= Utility.handleWeatherResponse(weatherstr);
            wid=weather.basic.weatherId;
            showWeatherInfo(weather);
        }else{
            String weatherId=getIntent().getStringExtra("weather_id");
            wid=weatherId;
            weatherLayout.setVisibility(View.INVISIBLE);
            requestWeather(weatherId);
        }

        String bingPic=prefs.getString("bing_pic",null);
        if(bingPic!=null){
            Glide.with(this).load(bingPic).into(bingPicimg);
        }else{
            loadpic();
        }

        swipeRefresh.setOnRefreshListener(()->{
            requestWeather(wid);
        });

        drawerLayout=findViewById(R.id.drawer_layout);
        navbtn=findViewById(R.id.nav_button);
        navbtn.setOnClickListener((v)->{
            drawerLayout.openDrawer(GravityCompat.START);
        });
    }

    private void showWeatherInfo(Weather weather){
        titleCity.setText(weather.basic.CityName);
        titleUpgradeTime.setText(weather.basic.update.loc.split(" ")[1]);
        degreeText.setText(weather.now.tmp+"℃");
        weatherInfoText.setText(weather.now.cond_txt);
        forecastLayout.removeAllViews();
        for(ForeCast foreCast:weather.forecastlist){
            View view= LayoutInflater.from(this).inflate(R.layout.forecast_item,forecastLayout,false);
            TextView dateText=view.findViewById(R.id.date_text);
            TextView infoTtext=view.findViewById(R.id.info_text);
            TextView maxText=view.findViewById(R.id.max_text);
            TextView minText=view.findViewById(R.id.mintext);
            dateText.setText(foreCast.date);
            infoTtext.setText(foreCast.more.info);
            maxText.setText(foreCast.tmp.max);
            minText.setText(foreCast.tmp.min);
            forecastLayout.addView(view);
        }
        if(weather.aqi!=null){
            aqiText.setText(weather.aqi.city.aqi);
            pm25text.setText(weather.aqi.city.pm25);
        }
        comforttext.setText("舒适度: "+weather.suggestion.comfort.info);
        carWashText.setText("洗车指数: "+weather.suggestion.cw.info);
        sportText.setText("运动建议: "+weather.suggestion.sport.info);
        weatherLayout.setVisibility(View.VISIBLE);
    }

    public void requestWeather(final String weatherId){
        String weatherUrl="http://guolin.tech/api/weather?cityid="+weatherId+"&key=b3acc927f57c412c87c4b47b9fa60a98";

        HttpUtil.sendOkHttpRequest(weatherUrl, new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                e.printStackTrace();
                runOnUiThread(()->{
                    Toast.makeText(WeatherActivity.this,"获取天气信息失败",Toast.LENGTH_SHORT).show();
                    swipeRefresh.setRefreshing(false);
                });
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                final String responseText=response.body().string();
                final Weather weather=Utility.handleWeatherResponse(responseText);
                runOnUiThread(()->{
                    if(weather!=null && weather.status.equals("ok")){
                        SharedPreferences.Editor editor=PreferenceManager.getDefaultSharedPreferences(WeatherActivity.this).edit();
                        editor.putString("weather",responseText);
                        editor.apply();
                        showWeatherInfo(weather);
                    }else{
                        Toast.makeText(getApplicationContext(),"获取天气信息失败",Toast.LENGTH_SHORT).show();
                    }
                    swipeRefresh.setRefreshing(false);
                });
            }
        });

        loadpic();
    }

    private void loadpic(){
        String url="http://guolin.tech/api/bing_pic";
        HttpUtil.sendOkHttpRequest(url, new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                    final String picu=response.body().string();
                    SharedPreferences.Editor edit=PreferenceManager.getDefaultSharedPreferences(WeatherActivity.this).edit();
                    edit.putString("bing_pic",picu);
                    edit.apply();
                    runOnUiThread(()->{
                        Glide.with(WeatherActivity.this).load(picu).into(bingPicimg);
                    });
            }
        });
    }


}
